<?php

require_once('config.inc');

/*
* class to handle site configuration
*/
class DB
{
	private static $instance;
	private $_dbConn;
	
	public static $ALL_ROWS = 184467440737; //random high number that's not realistic. ugly but works, mysql doesn't support omittion of Duration part of LIMIT...

	/*
	* private constructor
	* load the configuration file
	*/
	private function __construct()
	{
		$config = Config::getInstance();
		
		$this->_dbConn = mysql_connect(
			$config->get("./db/host"),
			$config->get("./db/user"),
			$config->get("./db/password") );

		if (!$this->_dbConn) 
			throw new Exception("cannot connect: ".mysql_error()."\n");

		$result = mysql_select_db($config->get("./db/database"),$this->_dbConn);

		mysql_query("SET NAMES 'utf8'");
		
		mysql_query("SET CHARACTER SET utf-8",$this->_dbConn);
		
		if (!$result) 
			throw new Exception("cannot select db: ".mysql_error()."\n");
		
		return true;
	}

	public static function getInstance()
	{
		if(!isset(self::$instance))
		{
			$object= __CLASS__;
			self::$instance=new $object;
		}
		return self::$instance;
	}

	/* 
	*  get a config value from the config file - using xpath.
	*/
	function getDB()
	{
		return $this->_dbConn;
	}

	//runs SQL and returns a list of associative arrays 
	function query($sql)
	{
		$query = mysql_query($sql,$this->_dbConn);

		$result = Array();

		if(!$query)
			return $result;
			
		while($row = mysql_fetch_assoc($query))
		{
			$rowArray = Array();

		    foreach(array_keys($row) as $key)
				$rowArray[$key] = $row[$key];

			$result[] = $rowArray;
		}

		return $result;	
	}
}

?>